package com.gym.myshop.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.gym.myshop.common.Const;
import com.gym.myshop.util.StrUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ming
 * 2021/11/5
 * description:验证码
 */
@WebServlet("/code")
public class CodeController extends BaseServlet {

    /**
     * @author:ming
     * @Date: 2021/11/5
     * @description:写出验证码图片 设置返回值为void ,BaseServlet父类就不会帮我们处理响应,需要自己处理
     */
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //验证码设置
        ValidateCode vc = new ValidateCode(120, 30, 4, 30);
        request.getSession().setAttribute(Const.VALI_CODE,vc.getCode());
        vc.write(response.getOutputStream());

    }

    /**
     *@author:ming
     *@Date: 2021/11/5
     *@description:验证用户输入验证码
     */
    public String checkCode(HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("code");
        String valiData = (String) request.getSession().getAttribute(Const.VALI_CODE);
        //判断用户输入验证码是否为空 以及用户输入验证码是否和系统保存的验证码一致
        if (StrUtils.isNotEmpty(code)&&code.equalsIgnoreCase(valiData)) {
            return Const.SUCCESS;
        }
        return Const.FAIL;
    }
}
